<template>
  <a-drawer v-model:visible="vdata.visible" width="40%" title="发放福分" :mask-closable="false" @close="close">
    <div class="container">
      <a-form
        ref="formRef"
        layout="vertical"
        :model="vdata.saveObject"
        :label-col="{ span: 24 }"
        :wrapper-col="{ span: 24 }"
        class="form"
        :rules="vdata.rules"
      >
        <a-row>
          <a-col :span="12">
            <a-form-item name="appId" label="小程序" :wrapper-col="{ span: 22 }">
              <GzAppIdSelect v-model:value="vdata.saveObject['appId']" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item name="name" label="福分名称" :wrapper-col="{ span: 22 }">
              <a-input v-model:value="vdata.saveObject['name']" placeholder="请输入福分名称" />
            </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
            <a-form-item name="agentNo" label="机构" :wrapper-col="{ span: 22 }">
              <GzAppIdSelect v-model:value="vdata.saveObject['agentNo']" />
            </a-form-item>
          </a-col> -->
          <a-col :span="24">
            <a-form-item name="fileList" :wrapper-col="{ span: 23 }">
              <template #label>
                <span style="margin-right: 20px">文件上传</span>
                <a-button type="link" style="padding:  4px 0;" @click="exportToExcel('发放福分模板',['小程序openid', '手机号', '积分值', '过期天数'],['','','',''])">
                  发放福分模板下载
                </a-button>
              </template>
              <a-upload-dragger
                :fileList="vdata.saveObject['fileList']"
                :action="vdata['action']"
                :data="vdata.formParams"
                :maxCount="1"
                bizType="template"
                accept=".xlsx, .xls"
                name="file"
                :beforeUpload="beforeUpload"
                @change="uploadChange"
              >
                <p class="ant-upload-drag-icon">
                  <InboxOutlined />
                </p>
                <p class="ant-upload-text">拖动到此处上传，或<a>点击上传</a></p>
                <p class="ant-upload-hint">
                  <b style="color: #ff4d4f">每次只能上传一个文件，</b>限制文件格式为XLS/XLSX。
                </p>
              </a-upload-dragger>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
  </a-drawer>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, getCurrentInstance } from 'vue'
import { exportToExcel } from '@/utils/excelUtils'
import { $getUploadFormParams } from '@/api/manage'
import { $apiSendScoreByFile } from '@/api/operateTool/index'
import { useUserStore } from '@/store/modules/user'

const { $infoBox } = getCurrentInstance()!.appContext.config.globalProperties

const vdata : any = reactive({
  visible: false,
  rules: {
    appId: [{ required: true, message: '请选择小程序', trigger: 'blur' }],
    name: [{ required: true, message: '请输入福分名称', trigger: 'blur' }],
    fileList: [{ required: true, message: '请上传文件', trigger: 'blur' }],
  },
  saveObject: {
    fileList: []
  },
  ossFileUrl: '',
  action: '', //上传地址
  formParams: '',
})

/**
 * 文件上传
 */
function beforeUpload(file) {
  vdata.saveObject.fileList = [file]
  // 校验小程序是否选择
  if (!vdata.saveObject.appId) {
    vdata.saveObject.fileList = []
    $infoBox.message.warn('请先选择小程序！')
    return false
  }
  // 校验文件大小 不大于20MB
  const isLt20M = file.size / 1024 / 1024 < 20
  if (!isLt20M) {
    vdata.saveObject.fileList = []
    $infoBox.message.warn('文件大小不能超过20MB！')
    return false
  }
  // 校验文件格式
  const isExcel = /\.(xlsx|xls)$/.test(file.name)
  if (!isExcel) {
    vdata.saveObject.fileList = []
    $infoBox.message.warn('文件格式必须为XLS/XLSX！')
    return false
  }
  return $getUploadFormParams(file, 'upload').then((res) => {
    vdata.action = res.formActionUrl // action
    vdata.formParams = res.formParams //表单组件
    vdata.ossFileUrl = res.ossFileUrl
  })
}

async function uploadChange(info) {
  if (info.file.status === 'error') {
    // 上传异常
    vdata.saveObject.fileList = []
    $infoBox.message.error('上传异常,请联系系统管理员')
  }

  if (info.file.status === 'done') {
    // 上传成功，发放福分
    sendScore()
  }
}
// 发放福分
async function sendScore() {
  try {
    myGlobalLoadingFunc(true)
    await $apiSendScoreByFile({ ossFileUrl: vdata.ossFileUrl, appId: vdata.saveObject.appId, name: vdata.saveObject.name })
    $infoBox.message.success('发放福分成功！')
  }finally {
    myGlobalLoadingFunc(false)
  }
}

// 关闭
const close = () => {
  vdata.visible = false
}

/**
 * 进度条
 * @param isShowGlobalLoadingVal 
 */
function myGlobalLoadingFunc(isShowGlobalLoadingVal) {
  useUserStore().setGlobalLoading(isShowGlobalLoadingVal)
}

/**
 * 展开
 */
async function show(record) {
  vdata.visible = true
}

defineExpose({
  show,
})
</script>
<style lang="less">
.form {
  margin: 30px;
  justify-content: center;
  overflow-y: auto;

  &::-webkit-scrollbar {
    display: none;
  }
}
</style>